package cn.jdemo.socket.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 同步非阻塞io
 * 当前示例，类似与select poll
 */
public class Demo01 {

    /**
     * 存放建立的tcp连接
     */
    static final List<SocketChannel> socketChannelList = new CopyOnWriteArrayList();;

    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);// 非阻塞
        serverSocketChannel.bind(new InetSocketAddress(8001));

        for(;;){
            SocketChannel accept = serverSocketChannel.accept();
            if (accept !=null){
                accept.configureBlocking(false);
                socketChannelList.add(accept);
            }
            /*
             * 弊端:
             * 1）遍历所有socket连接（可以增加selector,注册监听事件）
             * 2)若某个socket连接，处理业务耗时会影响后续连接(可以加线程池处理)
             */
            for (SocketChannel socketChannel : socketChannelList) {
                ByteBuffer byteBf = ByteBuffer.allocate(8);
                int read = socketChannel.read(byteBf);
                if (read != -1 && read != 0){
                    System.out.println(new String(byteBf.array(), 0,read));
                }
            }
        }
    }
}
